<?php


namespace app\controller;

use app\model\AlbumPic;
use app\model\File;
use app\model\SystemMenu;
use think\Controller;
use think\Db;
use think\facade\Env;

class System extends Controller
{
    protected $middleware = [
        'CheckLogin'  => ['except' => ['upload','getAlbum','getPicList','saveRemote','delAlbum','addAlbum'] ],
//        'Hello' => ['only' => ['hello'] ],
    ];
    // 获取初始化数据
    public function getSystemInit(){
        $homeInfo = [
            'title' => '首页',
            'href'  => '/admin/welcome',
        ];
        $logoInfo = [
            'title' => 'LAYUI MINI',
            'image' => '/static/img/logo.png',
        ];
//        $SystemMenuModel = new SystemMenu();
        $menuInfo = SystemMenu::menuTree();
        $systemInit = [
            'homeInfo' => $homeInfo,
            'logoInfo' => $logoInfo,
            'menuInfo' => $menuInfo,
        ];
        return json($systemInit);
    }
    //获取图标按钮文件
    public function getVariables()
    {
        $path = Env::get('root_path') . 'public/static/layuimini/lib/font-awesome-4.7.0/less/variables.less';
        $data = file_get_contents($path);
        return $data;
    }
    public function systemMenu()
    {
        if($this->request->isAjax()){
            $menuList = SystemMenu::getMenuList();
            return json(['code'=>0,'msg'=>'','count'=>count($menuList),'data'=>$menuList]);
        }
        return $this->fetch();
    }
    public function editSystemMenu($id=null,$pid=null)
    {
        if($id){
            $res = Db::name('system_menu')->where('id',$id)->field('id,pid,title,href,icon,target,sort,status')->find();
        }else if($pid){
            $res = ['id'=>'', 'pid'=>$pid, 'title'=>'', 'href'=>'', 'icon'=>'fa-adjust', 'target'=>'_self', 'sort'=>'', 'status'=>'1'];
        }else{
            $res = ['id'=>'', 'pid'=>1, 'title'=>'', 'href'=>'', 'icon'=>'fa-adjust', 'target'=>'_self', 'sort'=>'', 'status'=>'1'];
        }
        $this->assign('res',$res);
        return $this->fetch();
    }
    public function submitMenu()
    {
        $data = input();
        $res = SystemMenu::submit($data);
        return $res;
    }
    public function delMenu()
    {
        $id = input('id');
        $res = SystemMenu::delMenu($id);
        return $res;
    }
    public function upload()
    {
        $album_id = $this->request->param('album_id');
        $file = $this->request->file('file');
//        var_dump(getimagesize('/'.$file->getPath().$file->getFilename()));
        $filename = ($file->getInfo())['name'];
        $info = $file->validate([
            'size'=>209715200,
            'ext'=>'bmp,jpg,png,JPEG,jpeg,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,webp,avif,xls,xlsx,doc,pdf',
        ])->move( './uploads/images/');
        if($info){
            $path = '/uploads/images/'.$info->getSaveName();
            $size = $info->getSize();
            $real_path = Env::get('root_path') . 'public' . $path;
            $info = getimagesize($real_path);
            $pic = [
                'album_id'=>$album_id,
                'src' => $path,
                '_src' => $path,
                'width' => $info[0],
                'height' => $info[1],
                'name' =>$filename,
                'mime' => $info['mime'],
                'size' => $size
            ];
            $insert = AlbumPic::insertPic($pic);
            $res = ['code'=>$insert ? 200 : 202,'file'=>$pic,'msg'=>$insert ? '上传成功' : '上传失败'];
        }else{
// 上传失败获取错误信息
            $res = ['code'=>200,'file'=>'','filename'=>$filename,'msg'=>$file->getError()];
        }
        return json($res);
    }
    public function getAlbum()
    {
        $res = Db::name('album')->field('id,album_name')->select();
        return json($res);
    }
    public function getPicList()
    {
        $data = input();
        $res = Db::name('album_pic')
            ->field("id,album_id,src,_src,width,height,name,border,floatStyle,vspace,alt,style")
            ->where('album_id',$data['album_id'])
            ->paginate(20);
        return json($res);
    }
    public function addAlbum()
    {
        $name = input('name');
        $res = Db::name('album')->insertGetId(['album_name'=>$name]);
        return $res;
    }
    public function delAlbum($id=null){
        if(!$id) return json(['code'=>202,'msg'=>'缺少必要的id条件']);
        Db::startTrans();
        try{
            Db::name('album')->where('id',$id)->delete();
            Db::name('album_pic')->where('album_id',$id)->delete();
            Db::commit();
            $res = ['code'=>200,'msg'=>'删除成功'];
        }catch(\Exception $e){
            Db::rollback();
            $res = ['code'=>202,'msg'=>$e->getMessage()];
        }
        return json($res);
    }
    public function ueditorUpload()
    {
        $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents(Env::get('root_path') . "public/static/ueditor/config.json")), true);
        $action = input('action');
        switch ($action) {
            case 'config':
                $result =  $CONFIG;
                break;

            /* 上传图片 */
            case 'uploadimage':
                /* 上传涂鸦 */
            case 'uploadscrawl':
                /* 上传视频 */
            case 'uploadvideo':
                /* 上传文件 */
            case 'uploadfile':
                $result = $this->actionUpload($action,$CONFIG);
                break;

            /* 列出图片 */
            case 'listimage':
                $result = $this->actionList($action,$CONFIG);
                break;
            /* 列出文件 */
            case 'listfile':
                $result = $this->actionList($action,$CONFIG);
                break;
            /* 抓取远程文件 */
            case 'catchimage':
                $result = $this->actionCrawler($CONFIG);
                break;
            default:
                $result = json_encode(array(
                    'state'=> '请求地址出错'
                ));
                break;
        }
        if (isset($_GET["callback"])) {
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                return htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
            } else {
                return json_encode(array(
                    'state'=> 'callback参数不合法'
                ));
            }
        } else {
            return json($result);
        }
    }
    public function uploadfile()
    {
        $file = $this->request->file('file');
        $filename = ($file->getInfo())['name'];
        $info = $file->validate([
            'size'=>209715200,
            'ext'=>'xls,xlsx,doc,pdf,zip',
        ])->move( './uploads/files/');
        if($info){
            $path = '/uploads/files/'.$info->getSaveName();
            $size = getSize($info->getSize());
            $pic = [
                'src' => $path,
                '_src' => $path,
                'name' =>$filename,
                'mime' => mime_content_type($info->getRealPath()),
                'size' => $size
            ];
            $file = new File();
            $insert = $file->save($pic);
            $res = ['code'=>$insert ? 200 : 202,'file'=>$pic,'msg'=>$insert ? '上传成功' : '上传失败'];
        }else{
// 上传失败获取错误信息
            $res = ['code'=>202,'file'=>'','filename'=>$filename,'msg'=>$file->getError()];
        }
        return json($res);
    }
    public function getFileGroup()
    {
        $res = Db::name('file_group')->field('id,name as album_name')->select();
        return json($res);
    }
    public function getFileList()
    {
        $data = input();
        $res = Db::name('file')
            ->field("id,group_id as album_id,src,_src,name,size,name,mime")
            ->where('group_id',$data['album_id'])
            ->paginate(20);
        return json($res);
    }
    public function addFileGroup()
    {
        $name = input('name');
        $res = Db::name('album')->insertGetId(['album_name'=>$name]);
        return $res;
    }
    public function delFileGroup($id=null){
        if(!$id) return json(['code'=>202,'msg'=>'缺少必要的id条件']);
        Db::startTrans();
        try{
            Db::name('album')->where('id',$id)->delete();
            Db::name('album_pic')->where('album_id',$id)->delete();
            Db::commit();
            $res = ['code'=>200,'msg'=>'删除成功'];
        }catch(\Exception $e){
            Db::rollback();
            $res = ['code'=>202,'msg'=>$e->getMessage()];
        }
        return json($res);
    }
    public function actionUpload($action,$CONFIG)
    {
        $base64 = "upload";
        switch (htmlspecialchars($action)) {
            case 'uploadimage':
                $config = array(
                    "pathFormat" => $CONFIG['imagePathFormat'],
                    "maxSize" => $CONFIG['imageMaxSize'],
                    "allowFiles" => $CONFIG['imageAllowFiles']
                );
                $fieldName = $CONFIG['imageFieldName'];
                break;
            case 'uploadscrawl':
                $config = array(
                    "pathFormat" => $CONFIG['scrawlPathFormat'],
                    "maxSize" => $CONFIG['scrawlMaxSize'],
                    "allowFiles" => $CONFIG['scrawlAllowFiles'],
                    "oriName" => "scrawl.png"
                );
                $fieldName = $CONFIG['scrawlFieldName'];
                $base64 = "base64";
                break;
            case 'uploadvideo':
                $config = array(
                    "pathFormat" => $CONFIG['videoPathFormat'],
                    "maxSize" => $CONFIG['videoMaxSize'],
                    "allowFiles" => $CONFIG['videoAllowFiles']
                );
                $fieldName = $CONFIG['videoFieldName'];
                break;
            case 'uploadfile':
            default:
                $config = array(
                    "pathFormat" => $CONFIG['filePathFormat'],
                    "maxSize" => $CONFIG['fileMaxSize'],
                    "allowFiles" => $CONFIG['fileAllowFiles']
                );
                $fieldName = $CONFIG['fileFieldName'];
                break;
        }
        $up = new Uploader($fieldName,$config,$base64);
        return $up->getFileInfo();
    }
    public function actionList($action,$CONFIG)
    {
        switch ($action) {
            /* 列出文件 */
            case 'listfile':
                $allowFiles = $CONFIG['fileManagerAllowFiles'];
                $listSize = $CONFIG['fileManagerListSize'];
                $path = $CONFIG['fileManagerListPath'];
                break;
            /* 列出图片 */
            case 'listimage':
            default:
                $allowFiles = $CONFIG['imageManagerAllowFiles'];
                $listSize = $CONFIG['imageManagerListSize'];
                $path = $CONFIG['imageManagerListPath'];
        }
        $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);

        /* 获取参数 */
        $size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize;
        $start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0;
        $end = $start + $size;

        /* 获取文件列表 */
        $path = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "":"/") . $path;
        $files = getfiles($path, $allowFiles);
        if (!count($files)) {
            return json_encode(array(
                "state" => "no match file",
                "list" => array(),
                "start" => $start,
                "total" => count($files)
            ));
        }

        /* 获取指定范围的列表 */
        $len = count($files);
        for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--){
            $list[] = $files[$i];
        }
//倒序
//for ($i = $end, $list = array(); $i < $len && $i < $end; $i++){
//    $list[] = $files[$i];
//}

        /* 返回数据 */
        $result = array(
            "state" => "SUCCESS",
            "list" => $list,
            "start" => $start,
            "total" => count($files)
        );

        return $result;
    }
    public function actionCrawler($CONFIG)
    {
        set_time_limit(0);
        $config = array(
            "pathFormat" => $CONFIG['catcherPathFormat'],
            "maxSize" => $CONFIG['catcherMaxSize'],
            "allowFiles" => $CONFIG['catcherAllowFiles'],
            "oriName" => "remote.png"
        );
        $fieldName = $CONFIG['catcherFieldName'];

        /* 抓取远程图片 */
        $list = array();
        if (isset($_POST[$fieldName])) {
            $source = $_POST[$fieldName];
        } else {
            $source = $_GET[$fieldName];
        }
        foreach ($source as $imgUrl) {
            $item = new Uploader($imgUrl, $config, "remote");
            $info = $item->getFileInfo();
            array_push($list, array(
                "state" => $info["state"],
                "url" => $info["url"],
                "size" => $info["size"],
                "title" => htmlspecialchars($info["title"]),
                "original" => htmlspecialchars($info["original"]),
                "source" => htmlspecialchars($imgUrl)
            ));
        }

        /* 返回抓取数据 */
        return array(
            'state'=> count($list) ? 'SUCCESS':'ERROR',
            'list'=> $list
        );
    }
}